﻿using UnityEngine;
using System.Collections;

/// <summary>
/// https://en.wikipedia.org/wiki/Isometric_projection
/// 
/// 45度  35.264度
/// 
/// 128px --> 1m
/// 
/// 正方体 斜边长 sqrt(2)
/// 1/sqrt(2) = 0.707 缩放比例
/// 
/// 128px 64px 96px
/// 
/// 正方体 边长： sqrt(64^2 + 32^2) = 71.554 
/// 正方体 高度:  96/ 71.554 = 1.34164
/// 
/// 35.264 角度计算  sqrt(2)/2    sqrt(2 + 1)/2    cos(theta) =  sqrt(2) / sqrt(3)
/// 
/// 
/// 
/// 计算投影贴图每个像素对应的3D坐标 xyz 坐标：
/// 纹理坐标--》 camera坐标---》 屏幕投射射线 射到 cube上--》xyz 坐标 相对于cube的本地空间坐标
/// 获取mesh 上的UV 点位置 修改texture  Draw 
/// </summary>
public class Convert2DTo3D : MonoBehaviour {
    public SpriteRenderer sprite;
    public Camera mapCamera;
    public GameObject cubeMesh;

    public Texture2D blackTex;

    public int texWidth = 256;
    public int texHeight = 256;

    [ButtonCallFunc()]
    public bool Convert;
    public void ConvertMethod() {
        var tex = sprite.sprite.texture;
        var spPos = sprite.transform.position;

        //mapCamera.ViewportToWorldPoint();
        var allPixels = tex.GetPixels();
        var unit = 1/128.0f;
        var rayDir = Vector3.forward;
        //var mt = cubeMesh.GetComponent<MeshRenderer>().sharedMaterial.mainTexture;
        blackTex = new Texture2D(texWidth, texHeight);

        Debug.LogError("Pixel:"+unit+":"+spPos+":"+tex.width+":"+tex.height);
        //128pixel 1m
        //sprite 的锚点是中心
        for(var i = 0; i < tex.height; i++) {
            for(var j=0; j < tex.width; j++) {
                var py = (i-tex.height/2) * unit;
                var px = (j-tex.width/2) * unit;
                var pCol = allPixels[j+tex.width*i];

                var pPos = spPos + new Vector3(px, py, 0);

                //blackTex.SetPixel(j, i, pCol);
                //var viewPos = mapCamera.WorldToViewportPoint(pPos);
                var ray = new Ray(pPos, rayDir);
                RaycastHit hitInfo;
                var hitYet = Physics.Raycast(ray, out hitInfo, 100);
                if(hitYet) {
                    //var pos = hitInfo.point;
                    var texCoord = hitInfo.textureCoord;
                    texCoord.x *= blackTex.width;
                    texCoord.y *= blackTex.height;
                    pCol.a = 1;
                    blackTex.SetPixel((int)texCoord.x, (int)texCoord.y, pCol);

                }
            }
        }
        blackTex.Apply();
        //mapCamera.worldto

        var png = blackTex.EncodeToPNG();
        var path = System.IO.Path.Combine(Application.dataPath, "test.png");
        System.IO.File.WriteAllBytes(path, png);

    }
}
